package com.android.fragmentdemo.defineviews;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.text.style.ReplacementSpan;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class VerticalAlignTextSpan extends ReplacementSpan {
    private final int textColor;
    private final float leftSpace;
    private final float rightSpace;

    public VerticalAlignTextSpan(int textColor, float leftSpace, float rightSpace) {
        this.textColor = textColor;
        this.leftSpace = leftSpace;
        this.rightSpace = rightSpace;
    }

    @Override
    public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, @Nullable Paint.FontMetricsInt fm) {
        return (int) (paint.measureText(text, start, end) + leftSpace + rightSpace);
    }

    @Override
    public void draw(@NonNull Canvas canvas, CharSequence text,
                     int start, int end, float x, int top, int y,
                     int bottom, @NonNull Paint paint) {
        Paint.FontMetricsInt fontMetricsInt = paint.getFontMetricsInt();
        paint.setColor(textColor);
        paint.setAntiAlias(true);
        paint.setDither(true);
        float offsetY = (y + fontMetricsInt.ascent + y + fontMetricsInt.descent) / 2F - (top + bottom) / 2F;
        canvas.drawText(text, start, end, x + leftSpace, y - offsetY, paint);
    }
}
